'use strict'
var http = require('http');
var URL = require('url');
var queryString = require('querystring');

var httpApi = new function () {

    this.post = function (opts) {
        var http_opts = URL.parse(opts.url);
        http_opts.method = opts.method || "post";
        http_opts.headers = opts.headers || {};
        http_opts.headers["Content-Type"] = "application/x-www-form-urlencoded";
        http_opts.headers["user-agent"] = "nodejs http request";
        http_opts.sync = true;

        var dataLength = 0;
        var dataString = "";
        if (opts.params) {
            dataString = queryString.stringify(opts.params);
            dataLength = dataString.length;
        }
        http_opts.headers["Content-Length"] = dataLength;
        var req = http.request(http_opts, function (res) {
                res.setEncoding(opts.charset || 'utf-8');
                var datas = new Array();
                res.on("data", function (chunk) {
                    datas.push(chunk);
                });
                res.on('end', function () {
                    if ("function" === typeof opts.callback) {
                        var data = datas.join("");
                        if (opts.dataType && opts.dataType.toUpperCase() === "JSON") {
                            data = JSON.parse(data);
                        }
                        opts.callback(data);
                    }
                });
            }
        );
        req.on("error", function (e) {
            console.log(e);
            if ("function" === typeof opts.error) {
                opts.error(e);
            }
        })
        req.write(dataString)
        req.end();
        return this;
    };
    this.get = function (opts) {
        opts.method = "GET";
        return this.post(opts);
    }
};

exports = module.exports = httpApi;